<script setup>
import { ref, reactive, onMounted, watchEffect, watch } from "vue";
import PathInfo from "./pathInfo.vue";
import PathTree from "./pathTree.vue";
import CanvasPath from "./canvasPath.vue";
import PathList from "./pathList.vue";
// import { canvasData } from "./mockData";
import axios from "@/utils/request";
import { message } from "ant-design-vue";
import { getText } from "@/utils";
import { roleColorList } from "@/views/hangManage/prodTimeInfo/modules/prodTimeConfig";
import { cloneDeep, pick } from "lodash";
import i18n from '@/locales/index' 
const { t } = i18n.global

const moInfo = ref({}); // 制单信息
const operateType = ref("add"); // 操作类型 add edit view
const loading = ref(false);
const visible = ref(false); // 弹框开关属性
const params = ref({
  lineId: null,
  moId: null, // 制单ID
  processId: null,
  routeId: null, // 路线图ID
  switchType: false, // processId,routeId 手动变化
});
const cavasPathRef = ref(null); // canvas 组件
const pathInfoRef = ref(null); // PathInfo 组件
const pathTreeRef = ref(null); // PathTree 组件
const emits = defineEmits(["ok"]);
// 弹窗开启时操作
const open = async (record) => {
  operateType.value = record.type;
  visible.value = true;
  params.value.moId = record.moId;
  if (record.routeId) params.value.routeId = record.routeId;
  if (operateType.value == "view") params.value.routeId = record.id;
  await getMakeInfo(params.value.moId);
};
// 获取制单信息
const getMakeInfo = async (id) => {
  try {
    const res = await axios.getAction("/api/mo/mo/get", { id });
    moInfo.value = res.data || {};
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'));
    moInfo.value = {};
  }
};

const canvasDatas = reactive({
  canvasData: [],
  treeData: [],
});

const dealChidren = (data) => {
  data.forEach((item) => {
    operateType.value == "add"
      ? (item.title = `${item.lineNo}-${item.stationNo}, ${item.role}`)
      : (item.title = `${item.lineNo}-${item.stationNo}, ${getText(
          roleColorList,
          item.role,
          "value"
        )}`);
    item.key = item.id;
    item.label = `${item.lineNo}-${item.stationNo}`;
  });

  return data;
};

const dealData = (data) => {
  data.forEach((item) => {
    item.title = `${item.sortField}, ${item.processNo}, ${
      item.roadmapProcessName ? item.roadmapProcessName : item.name
    }  ${item.standardSeconds}${t('common.seconds')}`;
    // item.processNo = item.processNo;
    item.key = item.roadmapProcessId ? item.roadmapProcessId : item.id;
    item.processDetailId = item.id;
    item.forwardMerge = false; // 生效
    item.effect = true; // 合并工序
    delete item.id;
    if (item.children) {
      dealChidren(item.children);
    } else {
      item.children = [];
    }
  });

  return data;
};
const editDealData = (data) => {
  data.forEach((item) => {
    item.title = `${item.sort}, ${item.processNo}, ${
      item.roadmapProcessName ? item.roadmapProcessName : item.name
    }  ${item.standardSeconds ? item.standardSeconds : 0}秒`;
    item.key = item.id;
    item.children = item.moProcRoadmapProcStationList;
    delete item.moProcRoadmapProcStationList;
    if (item.children) {
      dealChidren(item.children);
    } else {
      item.children = [];
    }
  });

  return data;
};
// 路线图版本和流水线切换通知
const onLineProcesses = async (lineId, processId, switchType) => {
  params.value.lineId = lineId;
  params.value.processId = processId;
  params.value.switchType = switchType;
  // await getListProAndStation();
  // await getListAllStationAndProc();
};
// 站点新增/删除
const onTreeData = async (treeDatas) => {
  const copyArr = cloneDeep(treeDatas);
  const newArr = [];
  copyArr.forEach((item) => {
    item?.children.length > 0 &&
      item.children.forEach((jtm) => {
        newArr.push({
          processNo: item.processNo,
          roadmapProcessId:
            operateType.value == "add"
              ? item.roadmapProcessId
              : item.processRoadmapId,
          roadmapProcessName:
            operateType.value == "add" ? item.roadmapProcessName : item.name,
          sortField: operateType.value == "add" ? item.sortField : item.sort,
          standardSeconds: item.standardSeconds,
          role: jtm.role,
          stationId: jtm.stationId,
          stationNo: jtm.stationNo,
        });
      });
  });
  await getConvertToSimulatorData(newArr);
};
// 获取路线图列表
const getListProAndStation = async () => {
  if (operateType.value != "add" && !params.value.switchType) {
    try {
      const res = await axios.getAction("/api/mo/mo-proc-roadmap/get", {
        id: params.value.routeId,
      });
      if (+res.code === 200) {
        let formValue = pick(res.data, [
          "name",
          "section",
          "processId",
          "hangerLineIdList",
        ]);
        formValue.lineId = formValue.hangerLineIdList[0];
        delete formValue.hangerLineIdList;
        Object.assign(pathInfoRef.value.formState, formValue);

        res.data = editDealData(res.data.moProcRoadmapProcList);
        canvasDatas.treeData = res.data;

        onTreeData(res.data);
      }
    } catch (err) {
      console.log(err);
    }
  } else {
    try {
      const res = await axios.getAction("/api/mo/mo-proc/get", {
        id: params.value.processId,
      });
      if (+res.code === 200) {
        res.data = dealData(res.data.moProcDetailVOList);
        canvasDatas.treeData = res.data;
      }
    } catch (err) {
      console.log(err);
    }
  }
};
// 生成仿真路线图数据
const getConvertToSimulatorData = async (data) => {
  try {
    const res = await axios.postAction(
      "/api/mo/mo-simulator-proc-roadmap/convertToSimulatorData",
      {
        list: data,
        lineId: params.value.lineId,
      }
    );
    if (+res.code === 200) {
      res.data = dealData(res.data);
      canvasDatas.canvasData = res.data;
    } else {
      canvasDatas.canvasData = [];
    }
  } catch (err) {
    canvasDatas.canvasData = [];
    console.log(err);
  }
};
// 获取仿真路线图数据
// const getListAllStationAndProc = async () => {
//   try {
//     const res = await axios.postAction(
//       "/api/mo/mo-simulator-proc-roadmap/listAllStationAndProc",
//       params.value
//     );
//     if (+res.code === 200) {
//       res.data = dealData(res.data);
//       canvasDatas.canvasData = res.data;
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };
// 根据流水线ID获取站点列表
const stationList = ref([]);
const handleLineChange = async () => {
  if (params.value.lineId) {
    try {
      const res = await axios.postAction(
        "/api/device/station/get-hangerLineId-by-station",
        { hangerLineIdList: [params.value.lineId] }
      );
      res.data &&
        res.data.forEach((i) => {
          i.label = i.stationNo + "," + getText(roleColorList, i.role, "value");
          i.roleName = getText(roleColorList, i.role, "value");
          i.stationId = i.id;
          // i.mainStationBoolean = false
          i.receiveHangerBoolean = true;
          i.type = "0";
          i.proportion = 1;
          delete i.id;
        });
      // console.log(res.data, "----111111------");
      stationList.value = res.data || [];
      canvasDatas.canvasData = [];
    } catch {
      stationList.value = [];
    }
    // loading.value = false;
  }
};
// 弹框关闭时销毁数据
const pathModalCancel = () => {
  console.log("----关闭！！！-----");
  moInfo.value = {};
  params.value.lineId = null;
  params.value.moId = null;
  params.value.processId = null;
  canvasDatas.canvasData = [];
  canvasDatas.treeData = [];
  pathInfoRef.value = null;
  // cavasPathRef.value.reDraw(); // 清除canvas
  cavasPathRef.value = null;
  visible.value = false;
};
// 保存
const onPathModalConfirm = async () => {
  loading.value = true;
  try {
    await pathInfoRef.value.formRef.validate();
    let params = queryParams();
    if (operateType.value == "add") {
      const res = await axios.postAction(
        "/api/mo/mo-proc-roadmap/save",
        params
      );
      if (res.success) {
        message.success(res.msg || t('common.successTip'));
        loading.value = false;
        emits("ok");
        pathModalCancel();
      }
    } else {
      const res = await axios.postAction(
        "/api/mo/mo-proc-roadmap/edit",
        params
      );
      if (res.success) {
        message.success(res.msg || t('common.successTip'));
        loading.value = true;
        emits("ok");
        pathModalCancel();
      }
    }

    // loading.value = false;
  } catch (err) {
    console.log(err, "---保存失败----");
    loading.value = false;
  }
};
// 提交数据处理
const queryParams = () => {
  // let { tableList, processId } = roadmapListRef.value;
  console.log(pathTreeRef.value.treeData, "----pathTreeRef.value.treeData---");
  let paramsData = Object.assign({}, pathInfoRef.value.formState);
  let tableData = queryTableParams(cloneDeep(pathTreeRef.value.treeData));
  paramsData.moProcRoadmapProcList = tableData.newTableList;
  paramsData.hangerLineIdList = [paramsData.lineId];
  delete paramsData.lineId;
  paramsData.moId = params.value.moId;
  operateType.value == "add"
    ? delete paramsData.id
    : (paramsData.id = params.value.routeId);
  return paramsData;
};
const queryTableParams = (tableList) => {
  // let hangerLineList = [];
  tableList.forEach((item, index) => {
    item.sort = item.sort || index + 1;
    item.forwardIntegration = operateType.value == item.forwardMerge ? 1 : 0;
    item.enable = item.effect ? 1 : 0;
    item.moId = item.moId || params.value.moId;
    item.moProcRoadmapProcStationList = item.children || [];
    delete item.children;
    item.moProcRoadmapProcStationList.forEach((el, i) => {
      el.sort = i + 1;
      el.mainAuxiliaryStation = el.mainStationBoolean ? 2 : 1;
      // el.receiveHanger = el.receiveHangerBoolean ? 1 : 0;
      el.receiveHanger = 1;
      el.moId = el.moId || params.value.moId;
      // hangerLineList.push(el.hangerLineId);
    });
  });
  const newTableList = initTableList(tableList);
  return {
    newTableList,
    // hangerLineList: Array.from(new Set(hangerLineList)),
  };
};
const initTableList = (list, isNew) => {
  console.log(isNew, "----isNew---");
  let newList = cloneDeep(list);
  newList.forEach((i) => {
    i.open = true;
    i.forwardMerge = i.forwardIntegration == 1;
    // i.enable = isNew ? 1 : i.enable;
    i.enable = 1;
    i.effect = i.enable == 1;
    if (i.moProcRoadmapProcStationList) {
      i.moProcRoadmapProcStationList.forEach((i) => {
        i.mainStationBoolean = i.mainAuxiliaryStation == 2;
        i.receiveHangerBoolean = i.receiveHanger == 1;
      });
    } else {
      i.moProcRoadmapProcStationList = [];
    }
  });
  return newList;
};
onMounted(async () => {});

watchEffect(() => {
  if (params.value.lineId && params.value.processId) {
    getListProAndStation();
    // getListAllStationAndProc();
  }
});

// 流水线切换监听
watch(
  () => params.value.lineId,
  async (newVal) => {
    if (newVal) await handleLineChange();
  },
  { deep: true, immediate: true }
);
defineExpose({
  open,
});
</script>

<template>
  <a-modal
    v-model:visible="visible"
    :title="`${$t('components.simulationRoadmap')}(${
      operateType == 'add' ? $t('common.addNew') : operateType == 'edit' ? $t('common.editor') : $t('common.detail')
    })`"
    :width="1400"
    class="pathModal"
    centered
    @cancel="pathModalCancel"
    @ok="onPathModalConfirm"
  >
    <div class="modalContainer">
      <div class="left">
        <PathInfo
          ref="pathInfoRef"
          :operateType="operateType"
          :moInfo="moInfo"
          :moId="params.moId"
          @onLineProcesses="onLineProcesses"
        ></PathInfo>
      </div>
      <div class="center">
        <CanvasPath
          ref="cavasPathRef"
          id="canvas2"
          :operateType="operateType"
          :data="canvasDatas.canvasData"
          :divideCount="Math.ceil(canvasDatas.canvasData.length / 2)"
        ></CanvasPath>
        <PathList :data="canvasDatas.treeData"></PathList>
      </div>
      <div class="right">
        <PathTree
          ref="pathTreeRef"
          :operateType="operateType"
          :data="canvasDatas.treeData"
          :stationList="stationList"
          @onTreeData="onTreeData"
        ></PathTree>
      </div>
    </div>
    <template #footer>
      <a-button key="back" @click="pathModalCancel">{{$t('common.cancel')}}</a-button>
      <a-button
        v-if="operateType != 'view'"
        key="submit"
        type="primary"
        :loading="loading"
        @click="onPathModalConfirm"
        >{{$t('common.ok')}}</a-button
      >
    </template>
  </a-modal>
</template>

<style scoped lang="less">
.modalContainer {
  --sideWidth: 260px;
  display: flex;
}
.left {
  width: var(--sideWidth);
  padding-right: 20px;
}
.center {
  flex: 1;
  border-left: 1px solid #dddddd;
  border-right: 1px solid #dddddd;
}
.right {
  width: var(--sideWidth);
}
</style>
<style lang="less">
.pathModal {
  overflow: hidden !important;
}
</style>
